var temp_DragControltarget; var temp_Dragcontrol;
var countControls = 0;
var current_control;

jQuery(document).ready(function(){
	jQuery('#cp').propertygrid({  
		//url:'propertygrid_data.json',  
		showGroup:true  
	}); 

	/*jQuery('#my-form-builder').formbuilder({
	'save_url': '/example-save.php',
	'load_url': '/example-json.php',
	'useJson' : true
	});*/
	$("#my-form-builder ul").sortable({ 
		//opacity: 0.6, cursor: 'move',
		//connectWith: ".taxonomydiv li"
		containment: 'parent',
		forceHelperSize: true,
		forcePlaceholderSize: true,
		opacity: 0.8,
		placeholder: 'placeholder',
		connectWith: ".tools",
		revert: true,
		update: function(event, ui){
			//
			temp_DragControltarget = jQuery(ui.item).prev();
		}
	});

	jQuery(".tools").sortable({
		connectWith: "#my-form-builder ul",
		revert: true,
		helper: "clone",
		stop: function(event, ui){
			// check control type of current control
			// to make sure that we know this control when we add it
			//  
			temp_Dragcontrol = jQuery(ui.item).attr("data-type");
			setTimeout("insertControl()",200);
			return false; // return default to get back data
		}
	});

	//// add click handler
	event_Controls_LI_Click();


	jQuery(".tools li, #main_formbuilder li, #questions_editor").disableSelection().addClass("no_select");


	// init dialog properies windows
	jQuery('#dialog_proper').dialog({
		buttons:[{
			text:'Ok',
			iconCls:'icon-ok',
			handler:function(){
				alert('ok');
			}

		},{
			text:'Cancel',
			handler:function(){
				$('#dialog_proper').dialog('close');
			}
		}]
	}).dialog("close");  
});

function insertControl() {
	// where to insert
	var id=temp_DragControltarget.attr("id");
	var control;
	countControls++;
	var next_id = countControls;

	if (id != null)
		{
		// insert into right position
		control = jQuery("#"+id).after("<li id='id_"+next_id+"'></li>").next();
	}
	else
		{
		// insert at the end
		control = jQuery("#list").append("<li id='id_"+next_id+"'></li>").find(":last");
	}

	// now we insert control html
	appendNewField(control, temp_Dragcontrol);
	control.addClass("form-line no_select control").attr("data-type",temp_Dragcontrol);
	select_Control(control);
	// add click handler
	event_Controls_LI_Click(control);
}

// Wrapper for adding a new field
function appendNewField(control, type, values, options, required) {
	field = '';
	field_type = type;
	if (typeof (values) === 'undefined') {
		values = '';
	}

	if (eval('typeof append'+type) == 'function')
		{
		eval("append"+type+"(control, values, options, required )");
	}
	else
		{
		control.remove();
		countControls--;
		return;
	}
}

// insert label field
function appendLABEL (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; "><div  class="control_label">Click to edit</div></div>';
	// insert html
	control.html(html);
	// set control property

	// handle event
	control.find(".control_label").dblclick(function(){
		jQuery(this).hide().parent().append("<input type='text' value='"+jQuery(this).html()+"' class='text' style='width: 95%;'>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parent().find(".control_label").html(jQuery(this).val()).show();
				jQuery(this).remove();
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	}).parent().append(  appendPropertyDeleteControls());
};

function propertyLABEL(control){
	alert("Sorry, this control does not have settings.");
}

// insert label field
function appendHTMLTEXT(control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; "><div  class="control_label">Click to edit this HTML</div></div>';
	// insert html
	control.html(html);
	// add edit button

	// handle event
	control.find(".control_label").dblclick(function(){
		jQuery(this).parents("li.form-line").find(".button-container").children(":first").removeClass("index-edit").addClass("index-save");
		jQuery(this).hide().parent().append("<textarea class='text'>"+jQuery(this).html()+"</textarea>").find("textarea").cleditor({width:"100%", height:"100%"})[0].focus();
	}).parent().append(appendPropertyDeleteControls());

	// append edit button
	control.find(".button-container").prepend("<img src='/files/blank.gif' class='index-edit' title='Edit'>").find(".index-edit").click(function(){
		if (jQuery(this).hasClass("index-edit"))
			{
			jQuery(this).removeClass("index-edit").addClass("index-save").parents("li.form-line").find(".control_label").trigger("dblclick");
		}
		else
			{
			var tcontrols=jQuery(this).parents("li.form-line");
			var data=tcontrols.find("textarea").val();  
			tcontrols.find(".cleditorMain").remove();
			tcontrols.find(".control_label").html(data).show();
			jQuery(this).removeClass("index-save").addClass("index-edit");
		}
	});
};

function propertyHTMLTEXT(control){
	alert("Sorry, this control does not have settings.");
}

function appendTEXT (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="form-label-left">Double click to edit title</div>';
	html+='<div class="form-input"><div class="question-input"><input type="text" class="form-textbox text" size="20"></div></div>';
	html+='</div>';
	// insert html
	control.html(html);
	// set control property

	// handle event
	control.find(".form-label-left").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' '>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".form-label-left").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function propertyTEXT(control, parent){
	if (typeof control !="string") // call by event
	{
		showProperties(control,"Setting of Text control",function(){
			var grid = jQuery("#pro_grid").propertygrid('getChanges');
			for (var i=0; i<grid.length;i++)
				switch (grid[i].name){
					case "Default value":
						break;
					case "Require type":
						break;
				}
		});
	}
	else
	{
		// callback from showProperties, to build properties grid
		var html="<table id='pro_grid'></table>";
		jQuery(control).append(html);
		
		//
		control = jQuery("#pro_grid");
		control.propertygrid({
				width:480,
				height:200,
				showGroup:false,
				showHeader:false,
				scrollbarSize:0
		});
		
		// properties process
	   control.propertygrid('appendRow',{
			"name":"Default value",
			"value":parent.find("input[type='text']").val(),
			"editor":"text",
	   });  
	   
	   
	   
	   control.propertygrid('appendRow',{
			"name":"Require type",
			"value":"email",
			"editor":{
				type:'combobox',
				options:{
					valueField:'email_type',
					textField:'name',
					data:[
						{email_type:"",name: "Not required"},
						{email_type:"required",name: "Not empty string"},
						{email_type:"email",name: "Email"},
						{email_type:"date",name: "Date"},
						{email_type:"digits",name: "Digits"},
						{email_type:"number",name: "Number"},
						{email_type:"creditcard",name: "Credit Card"}
						]
					},
					required:true
				}  
			}
	   );  
	}
}

function appendTEXTAREA (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="form-label-left" style="display: block;">Double click to edit title</div>';
	html+='<div class="form-input"><div class="question-input"><textarea class="form-textbox text"  cols=30 rows=5></textarea></div></div>';
	html+='</div>';
	// insert html
	control.html(html);
	// set control property

	// handle event
	control.find(".form-label-left").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' '>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".form-label-left").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function appendCOMBOBOX (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="form-label-left" style="display: block;">Double click to edit title</div>';
	html+='<div class="form-input"><div class="question-input"><select class="text"><option value=1>Value 1</option><option value=2>Value 2</option><option value=3>Value 3</option></select></div></div>';
	html+='</div>';
	// insert html
	control.html(html);
	// set control property

	// handle event
	control.find(".form-label-left").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' '>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".form-label-left").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function appendCHECKBOX (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="control_label" style="display: block;">Double click to edit title</div>';
	html+='<div class="form-input"><div class="question-input"><INPUT TYPE=checkbox NAME="pizzasize" VALUE="S">small</div></div>';
	html+='</div>';
	// insert html
	control.html(html);
	// set control property

	// handle event
	control.find(".control_label").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' style='width: 94%;'>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".control_label").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function appendRATING (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="form-label-left" style="display: block;">Double click to edit title</div>';
	html+='<div class="form-input"><div id="rating_'+control.attr("id")+'" class="rating"></div></div>';
	html+='</div>';
	// insert html
	control.html(html);
	// cal rating
	control.find("#rating_"+control.attr("id")).raty({
		start:    2,
		path : '/js/jquery_rating/img/',
		starOn:   'medal-on.png',
		starOff:  'medal-off.png'
	});

	// handle event
	control.find(".form-label-left").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' style='width: 94%;'>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".form-label-left").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function appendRADIOBOX (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="control_label" style="display: block;">Double click to edit title</div>';
	html+='<div class="form-input"><div class="question-input"><INPUT TYPE=radio NAME="pizzasize" VALUE="S">small</div></div>';
	html+='</div>';
	// insert html
	control.html(html);
	// set control property

	// handle event
	control.find(".control_label").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' style='width: 94%;'>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".control_label").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function appendMATRIX_generate_control(control){
	// read configure
	var cols = control.find("input[name='cols']").val().split("|");
	var rows = control.find("input[name='rows']").val().split("|");
	var col_percent = 100/cols.length;
	var html=" \
	<div class=\"form-input-wide\"> \
	<div class=\"question-input\"> \
	<table cellpadding=4 cellspacing=0 class='form-matrix-table'> \
	<tbody>";

	for (var i=0;i<rows.length;i++)
	{
		html+="<tr>";
		for (var j=0;j<cols.length+1;j++)
		{
			var shtml="";

			if (i ==0 && j==0)
				shtml="<th style='border:none'>&nbsp;</th>";
			else if ((i==0) && (j>0)) // begin of each column
				shtml="<th class='form-matrix-column-headers' style='width:"+col_percent+"%'>"+cols[j-1]+"</th>";
			else if ((j ==0) && (i>0)) // begin of each row
				shtml="<th align='left' class='form-matrix-row-headers' nowrap='nowrap'>"+rows[i]+"</th>";
			else
				shtml="<td align='center' class='form-matrix-values'><input class='form-radio' type='radio'></td>";

			// insert 
			html+=shtml;

		}
		html+="</tr>";
	}
	html+="</tbody> \
	</table> \
	</div> \
	</div>";

	var  my_control = control.find(".form-input-wide");
	if (my_control.length)
		my_control.html(html);
	else
		control.find(".control_label").after(html);
}

function appendMATRIX (control, values, options, required) {
	var html='<div style="display: inline-block; width: 100%; ">';
	html+='<div  class="control_label" style="display: block;">Double click to edit title</div>';
	html+='</div>';

	// default configure
	var rows="Service Quality|Overall Hygiene|Responsiveness|Kindness and Helpfulness";
	var cols = "Very Satisfied|Satisfied|Somewhat Satisfied|Not Satisfied";
	// insert html
	control.html(html);
	append_hiddenField(control, 'rows', rows);
	append_hiddenField(control, 'cols', cols);
	appendMATRIX_generate_control(control);
	// set control property

	// handle event
	control.find(".control_label").dblclick(function(){
		var val = jQuery(this).html();
		jQuery(this).html("<span style='display: none;'>"+val+"</span>");
		jQuery(this).append("<input type='text' value='"+val+"' class='text' style='width: 94%;'>").find("input").focus().focusout(function(){
			jQuery(this).fadeOut(300,function(){ 
				jQuery(this).parents(".control_label").html(jQuery(this).val());
			});
		}).keydown( function (event) { 
			if(event.which == 13) {
				event.preventDefault();
				jQuery(this).trigger("focusout");
			}
		});
	});
	control.append(  appendPropertyDeleteControls());
};

function append_hiddenField(control, name, value){
	control.append("<input type=hidden name='"+name+"' value='"+value+"'>");
}

function appendPropertyDeleteControls ()
{
	var html='<div class="button-container"><img src="/files/blank.gif" class="form-propbutton index-gear" title="Settings"><img src="/files/blank.gif" class="form-delbutton index-cross" title="Remove"></div>';
	return html;
}
/* Events */
function select_Control(control){
	jQuery("#list li").removeClass("question-selected").find(".button-container").hide();
	jQuery(control).addClass("question-selected").find(".button-container").show();
}

function event_Controls_LI_Click(control){
	jQuery("#list li").click(function(){
		jQuery("#list li").removeClass("question-selected").find(".button-container").hide();
		jQuery(this).addClass("question-selected").find(".button-container").show();
	});

	if (typeof control != 'undefined'){
		// remove control action
		control.find(".form-delbutton").click(function(){
			jQuery(this).parents("li.form-line").fadeOut(500, function(){
				jQuery(this).remove();
			})
		}); 

		// properties button
		control.find(".form-propbutton").click(function(){
			var control = jQuery(this).parents("li.form-line");
			var data_type = control.attr("data-type");

			//
			if (eval('typeof property'+data_type) == 'function')
				{
				eval("property"+data_type+"(control)");
			}   
		});
	}
}

/* end Events */

/* Properties */
/**
* ok_callback : function (properties_obj)
*/
function showProperties(control, title, ok_callback, width, height )
{

	if (typeof width == 'undefined')
		width=500;
	if (typeof height == 'undefined')
		height=300;        

	if (typeof height == 'undefined')
		ok_callback = function(pro_obj){};

	if (typeof title == 'undefined')
		title = "Settings";

	if (typeof control == 'undefined'){
		alert("Error");
		return;
	}

	current_control = control;
	
	var html="<div id='dialog_proper' title='"+title+"' modal='true' style='width:"+width+"px;height:"+height+"px;' rel='"+control.attr("id")+"'>  \
	<div id='proper_grid'></div> \
	</div>  ";
	
	// remove old dialog
	jQuery("#dialog_proper").remove();
	// create new one
	jQuery("body").append(html);
	
	// init js
	dialog = jQuery("#dialog_proper");
	
	// callback to build properties grid
	eval("property"+control.attr("data-type")+"('#proper_grid', control);");
	
	dialog.dialog({
		buttons:[{
					text:'Ok',
					iconCls:'icon-ok',
					handler:ok_callback
				},{
					text:'Cancel',
					handler:function(){
						$('#dialog_proper').dialog('close');
					}
				}]
	});
}
/* End of propries*/

